package iot

import (
	"github.com/go-netty/go-netty"
	"github.com/go-netty/go-netty/codec"
	"github.com/go-netty/go-netty/utils"
)

// PacketCodec create packet codec
func PacketCodec(maxFrameLength int) codec.Codec {
	utils.AssertIf(maxFrameLength <= 0, "maxFrameLength must be a positive integer")
	return &packetCodec{maxFrameLength: maxFrameLength, buffer: make([]byte, maxFrameLength)}
}

type packetCodec struct {
	maxFrameLength int
	buffer         []byte
}

func (*packetCodec) CodecName() string {
	return "packet-codec"
}

func (p *packetCodec) HandleRead(ctx netty.InboundContext, message netty.Message) {
	reader := utils.MustToReader(message)
	n, err := reader.Read(p.buffer)
	if nil != err || n == 0 {
		ctx.Close(err)
		// ctx.Attachment()
		return
	}
	// logx.Info(p.buffer[:n])
	ctx.HandleRead(p.buffer[:n])
}

func (*packetCodec) HandleWrite(ctx netty.OutboundContext, message netty.Message) {
	ctx.HandleWrite(message)
}
